package br.com.mtech.ctrlliberty.web.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import br.com.mtech.ctrlliberty.clientjar.util.Util;
@FacesConverter(value="dateConverter")
public class DateConverter implements Converter {
      
      public Object getAsObject(FacesContext context, UIComponent component, String valor) {
          if (Util.isEmpty(valor)){
        	  return null;
          }

          String sDate = valor.replaceAll("[a-z,A-Z, ,-,,/]+","");
          String day = sDate.substring(0,2);
          String month = sDate.substring(2,4);
          String year = sDate.substring(4);
          Calendar data = Calendar.getInstance();
          data.set(Integer.parseInt(year),Integer.parseInt(month) -1,Integer.parseInt(day));
          
          return data;
      }
      
      public String getAsString(FacesContext context, UIComponent component, Object value) {
    	  
    	  Calendar cal = (Calendar) value;
    	  
    	  SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    	  return sdf.format(cal.getTime());
      }
}